package com.ryan.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPayUtil;
import com.ryan.exception.TravelException;
import com.ryan.order.entity.Order;
import com.ryan.order.entity.PayLog;
import com.ryan.order.feignclient.RouteClient;
import com.ryan.order.mapper.PayLogMapper;
import com.ryan.order.service.OrderService;
import com.ryan.order.service.PayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryan.order.utils.HttpClient;
import com.ryan.utils.vo.OrderRoute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author ryan
 * @since 2020-07-31
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private RouteClient routeClient;

    @Autowired
    private OrderService orderService;

    /**
     * 条件+分页查询所有的支付记录
     * @param pageIndex
     * @param pageSize
     * @param orderNo
     * @return
     */
    @Override
    public Page<PayLog> getOrderList(long pageIndex, long pageSize, String orderNo) {

        QueryWrapper<PayLog> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        if(!StringUtils.isEmpty(orderNo)){
            wrapper.eq("order_no", orderNo);
        }
        Page<PayLog> page = new Page<>(pageIndex, pageSize);
        baseMapper.selectPage(page, wrapper);
        return page;
    }

    /**
     * 根据订单号生成微信支付二维码
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, Object> createNative(String orderNo) {
        try{
            //根据orderNo查询订单信息
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo);
            Order order = orderService.getOne(wrapper);
            //设置支付参数
            Map m = new HashMap();
            m.put("appid","wx74862e0dfcf69954");//微信公众号appid
            m.put("mch_id", "1558950191");//商户号id
            m.put("nonce_str", WXPayUtil.generateNonceStr());//微信工具类生成的随机签名，保证每一个订单都不一样
            m.put("body", order.getRouteTitle());
            m.put("out_trade_no", orderNo); //订单号
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            m.put("trade_type", "NATIVE");
            //HTTPClient来根据URL访问第三方接口并且传递参数微信支付提供的固定的地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数，并发送请求,将map集合转换为xml格式，并且需要商户key
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);//支持Https，默认是不支持的
            client.post();//发送请求
            //获取返回数据,注意返回的数据也是xml数据，后面还需要转换为map
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //封装结果集
            Map map = new HashMap();
            map.put("out_trade_no", orderNo);
            map.put("route_id", order.getRouteId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));  //返回二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));        //二维码地址

            return map;
        }catch(Exception e){
            throw new TravelException(20001, "支付失败");
        }
    }

    /**
     * 查询订单状态
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, String> queryOrderStatus(String orderNo) {

        try {
            //1 封装数据
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2 发送httpclient
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3 得到请求返回内容并转换为map返回
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map再返回
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 支付成功后，更新订单支付状态
     * @param map
     */
    @Override
    public void updatePayStatus(Map<String, String> map) {
        //获取订单号
        String orderNo = map.get("out_trade_no");
        //首先根据订单号查询支付订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        Order order = orderService.getOne(wrapper);
        //判断支付状态值
        if(order.getStatus().intValue() == 1){return;}//如果状态值为1，则表示已支付，不需要往下执行了

        //如果不是1则设置支付状态1
        order.setStatus(1);

        //同时将该路线的销量+1
        String routeId = order.getRouteId();
        //通过id获取该路线
        OrderRoute orderRoute = routeClient.getRouteById(routeId);
        orderRoute.setBuyCount(orderRoute.getBuyCount() + 1L);
        routeClient.updateBuyCount(orderRoute);

        orderService.updateById(order);
        //记录支付日志
        //向支付表添加支付记录
        PayLog payLog = new PayLog();
        payLog.setOrderNo(orderNo);  //订单号
        payLog.setPayTime(new Date()); //订单完成时间
        payLog.setPayType(1);//支付类型 1微信
        payLog.setTotalFee(order.getTotalFee());//总金额(分)

        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id")); //流水号
        payLog.setAttr(JSONObject.toJSONString(map));

        baseMapper.insert(payLog);
    }
}
